<template>
  <div class="login_container">
    <div class="login_box">
      <div class="left_content">
        <h1>{{ setting.title }}</h1>
        <h2>Open system management</h2>
        <h3>注册</h3>
        <el-form :model="registerForm" :rules="rules" ref="registerForms" class="register-form">
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="账号" v-model="registerForm.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" :prefix-icon="Lock" placeholder="密码" v-model="registerForm.password"
                      show-password></el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input type="password" :prefix-icon="Lock" placeholder="确认密码" v-model="registerForm.confirmPassword"
                      show-password></el-input>
          </el-form-item>
          <el-form-item prop="name">
            <el-input :prefix-icon="User" placeholder="昵称" v-model="registerForm.name"></el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input :prefix-icon="Iphone" placeholder="手机号" v-model="registerForm.phone"></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input :prefix-icon="Message" placeholder="邮箱" v-model="registerForm.email"></el-input>
          </el-form-item>
          <!-- 验证码模块 -->
          <el-form-item prop="checkcode" v-if="isShowCode" class="code-item">
            <el-input placeholder="验证码" :prefix-icon="CircleCheck" v-model.trim="registerForm.checkcode"
                      style="width: 60%"></el-input>
            <div class="login-code">
              <img :src="checkCodeUrl" @click="getCode()"/>
            </div>
          </el-form-item>
          <el-form-item class="submit-btn">
            <el-button :loading="loading" class="login_btn" type="primary" @click="registerApi">注册</el-button>
          </el-form-item>
        </el-form>
        <div class="login-link">
          已有账号？<router-link to="/login">立即登录</router-link>
        </div>
      </div>
      <div class="right_content">
        <img src="../../../assets/images/login_bg.svg" alt="login background">
      </div>
    </div>
  </div>
</template>

<script setup>
//引入设置标题与logo这配置文件
import {CircleCheck, Lock, User, Message, Iphone} from '@element-plus/icons-vue';
import {onMounted, ref} from 'vue';
import {useRouter} from 'vue-router';
import {ElNotification} from 'element-plus';
//引入用户相关的小仓库
import useUserStore from "@/store/modules/user.js";
import {checkCode,register} from "@/api/user/index.js";
import setting from "@/setting.js";
import {getSystemConfig} from "@/api/system/config/index.js";

let useStore = useUserStore();
//是否显示验证码
let isShowCode = ref(true);
//获取el-form组件
let registerForms = ref();
//获取路由器
let $router = useRouter();
//定义变量控制按钮加载效果
let loading = ref(false);
//收集注册数据
let registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  name: '',
  phone: '',
  email: '',
  checkcode: '',
  uuid: ''
});
//验证码图片(存的是一个路径)
let checkCodeUrl = ref();

const isShowCodeApi = async () => {
  getSystemConfig('CheckCode').then(res => {
    if (res.code === setting.SYSTEM_SUCCESS && res.data === 'false') {
      isShowCode.value = false;
      return false;
    }
    return true;
  })
}

//注册按钮回调
const registerApi = async () => {
  if (loading.value === true) {
    return;
  }

  //保证全部表单相校验通过再发请求
  await registerForms.value.validate();

  //检查密码是否一致
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    ElNotification({
      type: 'error',
      message: '两次输入的密码不一致'
    });
    return;
  }

  //加载效果:开始加载
  loading.value = true;

  try {
    //调用注册接口
    await register(registerForm.value);

    //注册成功提示信息
    ElNotification({
      type: 'success',
      message: '注册成功，请登录'
    });

    //跳转到登录页面
    $router.push({path: '/login'});

    //注册成功加载效果也消失
    loading.value = false;
  } catch (error) {
    //注册失败加载效果消息
    loading.value = false;
    //注册失败的提示信息
    ElNotification({
      type: 'error',
      message: error.message
    })
    getCode();
  }
}

//自定义校验规则函数
const validatorUserName = (rule, value, callback) => {
  try {
    // 检查是否包含中文字符
    const chineseRegex = /[\u4e00-\u9fa5]/;
    if (chineseRegex.test(value)) {
      callback(new Error('账号不能包含中文字符'));
    }
    if (value.length >= 5) {
      callback();
    } else {
      callback(new Error('账号长度至少五位'));
    }
  } catch {
    callback(new Error('请输入账号'));
  }
}

const validatorPassword = (rule, value, callback) => {
  try {
    if (!value) {
      callback(new Error('请输入密码'));
      return;
    }

    // 检查密码长度
    if (value.length < 6) {
      callback(new Error('密码长度至少六位'));
      return;
    }

    // 检查是否包含中文字符
    const chineseRegex = /[\u4e00-\u9fa5]/;
    if (chineseRegex.test(value)) {
      callback(new Error('密码不能包含中文字符'));
      return;
    }

    callback(); // 密码合法
  } catch {
    callback(new Error('请输入密码'));
  }
}

const validatorPhone = (rule, value, callback) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!value) {
    callback(new Error('请输入手机号'));
  } else if (!phoneRegex.test(value)) {
    callback(new Error('请输入有效的手机号码'));
  } else {
    callback();
  }
}

const validatorEmail = (rule, value, callback) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!value) {
    callback(new Error('请输入邮箱'));
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入有效的邮箱地址'));
  } else {
    callback();
  }
}

const validatorCheckCode = (rule, value, callback) => {
  if (value) {
    if (value.length != 4) {
      callback(new Error('验证码长度为四位'));
    } else {
      callback();
    }
  } else {
    callback(new Error('请输入验证码'));
  }
}

//定义表单校验需要配置对象
const rules = {
  username: [
    {trigger: 'blur', validator: validatorUserName}
  ],
  password: [
    {trigger: 'blur', validator: validatorPassword}
  ],
  confirmPassword: [
    {trigger: 'blur', validator: validatorPassword}
  ],
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    {trigger: 'blur', validator: validatorPhone}
  ],
  email: [
    {trigger: 'blur', validator: validatorEmail}
  ],
  checkcode: [
    {trigger: 'blur', validator: validatorCheckCode}
  ]
}

//获取验证码
const getCode = async () => {
  const result = await checkCode()
  if (result.code == setting.SYSTEM_SUCCESS) {
    checkCodeUrl.value = "data:image/gif;base64," + result.data.img
    registerForm.value.uuid = result.data.uuid
  }
}

onMounted(() => {
  if (isShowCodeApi()) {
    getCode();
  }
})
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: linear-gradient(to bottom right, #cbe0f5, #f0f2f5);
  display: flex;
  align-items: center;
  justify-content: center;

  .login_box {
    width: 1000px;
    height: 600px;  // Increased height to accommodate more fields
    background: #fff;
    border-radius: 16px;
    display: flex;
    box-shadow: 0 8px 24px rgba(149, 157, 165, 0.1);
    overflow: hidden;

    .left_content {
      width: 50%;
      padding: 30px 40px;
      background: #fff;
      overflow-y: auto;  // Add scroll if content is too long
      display: flex;
      flex-direction: column;

      h1 {
        font-size: 24px;
        color: #333;
        margin-bottom: 8px;
      }

      h2 {
        font-size: 14px;
        color: #999;
        margin-bottom: 16px;
      }

      h3 {
        font-size: 16px;
        color: #333;
        margin-bottom: 24px;
        font-weight: bold;
      }

      .register-form {
        flex: 1;
        display: flex;
        flex-direction: column;

        .el-form-item {
          margin-bottom: 16px;

          :deep(.el-input__wrapper) {
            background-color: #f5f7fa;
            border: none;
            box-shadow: none;
            height: 40px;

            .el-input__inner {
              height: 40px;
              line-height: 40px;
            }
          }
        }

        .code-item {
          display: flex;
          align-items: center;

          .el-input {
            flex: 1;
            margin-right: 10px;
          }

          .login-code {
            width: 120px;
            height: 40px;

            img {
              width: 100%;
              height: 100%;
              cursor: pointer;
              border-radius: 4px;
              border: 1px solid #eee;
            }
          }
        }

        .submit-btn {
          margin-top: 10px;

          .login_btn {
            width: 100%;
            height: 42px;
            border-radius: 4px;
            background: #6c5ce7;
            border: none;
            font-size: 16px;
            font-weight: 500;

            &:hover {
              background: #5b4cc4;
            }
          }
        }
      }

      .login-link {
        text-align: center;
        margin-top: 20px;
        color: #666;
        font-size: 14px;

        a {
          color: #6c5ce7;
          text-decoration: none;
          font-weight: 500;
          margin-left: 5px;

          &:hover {
            text-decoration: underline;
          }
        }
      }
    }

    .right_content {
      flex: 1;
      background: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 200%;
        height: 200%;
        border-radius: 50%;
        z-index: 0;
      }

      img {
        width: 86%;
        height: auto;
        position: relative;
        z-index: 1;
      }
    }
  }
}
</style>